package edu.fiu.cis.personalize.server;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

public final class GraphUpdater {

	private static final int MAX_UPDATES = 100;

	private static ConcurrentLinkedQueue<UpdateElement> updateQueue = new ConcurrentLinkedQueue<UpdateElement>();

	public static void enque(UpdateElement e) {
		updateQueue.add(e);
	}

	public static synchronized int processUpdates() {
		// if (GraphMediator.inUse()) {
		// return -1;
		// }

		if (updateQueue.isEmpty()) {
			return 0;
		}

		GraphMediator.setInUpdate(true);

		Set<UpdateElement> updateList = new HashSet<UpdateElement>();

		while (!updateQueue.isEmpty() || updateList.size() < MAX_UPDATES) {
			updateList.add(updateQueue.poll());
		}

		GraphMediator.persist(updateList);

		GraphMediator.setInUpdate(false);

		// process update on berkeley DB ( no need to stop users for this).

		return updateList.size();

	}

}
